const express = require('express');
const router = express.Router();
const noticeMapper = require('../mapper/noticeMapper');
const conn = require('../utils/conn');
const jwt = require('../utils/jwt');

router.post('/v1/notice', (req, res) => {
  const validate = jwt.validate(req, res);
  if(validate < 1) {
    return;
  }

  const { title, content, userId, isTop } = req.body;
  if(validate != userId) {
    return res.send({ code: 418, err: "I'm a teapot" });
  }
  conn.query(noticeMapper.add, [ title, content, userId, isTop ], (err, data) => {
    if(err) {
      res.send({ code: 500, err });
    } if (data) {
      res.send({ code: 200, data });
    }
  });
});

router.put('/v1/notice', (req, res) => {
  const validate = jwt.validate(req, res);
  if(validate < 1) {
    return;
  }

  const { title, content, isTop, id } = req.body;
  conn.query(noticeMapper.add, [ title, content, isTop, id ], (err, data) => {
    if(err) {
      res.send({ code: 500, err });
    } if (data) {
      res.send({ code: 200, data });
    }
  });
});

router.get('/v1/notice', (req, res) => {
  const { page, size } = req.query;
  conn.query(noticeMapper.select, [ (page - 1) * size, size ], (err, data) => {
    if(err) {
      res.send({ code: 500, err });
    } if(data && data.length == size) {
      conn.query(noticeMapper.count, [], (err, result) => {
        if(err) {
          res.send({ code: 500, err });
        } if(result && result.length) {
          res.send({ code: 200, data, count: result[0].total });
        }
      });
    } else if(data) {
      res.send({ code: 200, data, count: data.length });
    }
  });
});

router.delete('/v1/notice/:id', (req, res) => {
  const validate = jwt.validate(req, res);
  if(validate < 1) {
    return;
  }
  
  const id = req.params.id;
  conn.query(noticeMapper.delete, [id], (err, data) => {
    if(err) {
      res.send({ code: 500, err });
    } if(data) {
      res.send({ code: 200, data });
    }
  })
});

module.exports = router;